using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;

using InformationSchema;

namespace Core
{
    public class Table
    {
        private string schema = string.Empty;
        private string name = string.Empty;
        private long rows = 0;
        private DateTime create_time;
        private DateTime update_time;
        private string comment = string.Empty;

        public string Name
        {
            get { return name; }
        }

        public string Schema
        {
            get { return schema; }
        }

        public long Rows
        {
            get { return rows; }
        }

        public DateTime CreateTime
        {
            get { return create_time; }
        }

        public DateTime UpdateTime
        {
            get { return update_time; }
        }

        public string Comment
        {
            get { return comment; }
        }

        private static Table CreateFromReader(DbDataReader reader)
        {
            Table table = new Table();

            table.schema = reader.GetString(0);
            table.name = reader.GetString(1);
            if (!reader.IsDBNull(2)) table.rows = reader.GetInt64(2);
            if (!reader.IsDBNull(3)) table.create_time = reader.GetDateTime(3);
            if (!reader.IsDBNull(4)) table.update_time = reader.GetDateTime(4);
            if (!reader.IsDBNull(5)) table.comment = reader.GetString(5);

            return table;
        }

        public static List<Table> FindAll()
        {
            string query = "SELECT T.`TABLE_SCHEMA`, T.`TABLE_NAME`, T.`TABLE_ROWS`, T.`CREATE_TIME`, T.`UPDATE_TIME`, T.`TABLE_COMMENT` FROM information_schema.`TABLES` T";
            List<Table> tables = new List<Table>();

            using (DbDataReader reader = DatabaseHelper.ExecuteReader(query))
            {
                while (reader.Read())
                {
                    tables.Add(CreateFromReader(reader));
                }
            }

            return tables;

        }
    }
}
